package com.cnswhy.cloud.auth.configure;

import com.cnswhy.cloud.auth.properties.CnswhyAuthProperties;
import com.cnswhy.cloud.auth.properties.CnswhyClientsProperties;
import com.cnswhy.cloud.auth.service.CnswhyUserDetailService;
import com.cnswhy.cloud.auth.service.RedisUidGenerator;
import com.cnswhy.cloud.auth.translator.CnswhyWebResponseExceptionTranslator;
import com.cnswhy.cloud.common.datasource.service.UidGenerator;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.builders.InMemoryClientDetailsServiceBuilder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

@Configuration
@EnableAuthorizationServer//开启认证服务器相关配置
public class CnswhyAuthorizationServerConfigure extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisConnectionFactory redisConnectionFactory;
    @Autowired
    private CnswhyUserDetailService userDetailService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private CnswhyAuthProperties cnswhyAuthProperties;
    @Autowired
    private CnswhyWebResponseExceptionTranslator cnswhyWebResponseExceptionTranslator;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        CnswhyClientsProperties[] clientsArray = cnswhyAuthProperties.getClientsProperties();
        InMemoryClientDetailsServiceBuilder builder = clients.inMemory();
        if(ArrayUtils.isNotEmpty(clientsArray)){
            for (CnswhyClientsProperties client : clientsArray) {
                if (StringUtils.isBlank(client.getClient())) {
                    throw new Exception("client不能为空");
                }
                if (StringUtils.isBlank(client.getSecret())) {
                    throw new Exception("secret不能为空");
                }
                String[] grantTypes = StringUtils.splitByWholeSeparatorPreserveAllTokens(client.getGrantType(), ",");
                builder.withClient(client.getClient())
                        .secret(passwordEncoder.encode(client.getSecret()))
                        .authorizedGrantTypes(grantTypes)
                        .scopes(client.getScope());
            }
        }
        /*clients.inMemory()
                .withClient("cnswhy")
                .secret(passwordEncoder.encode("Zzc.2020"))
                .authorizedGrantTypes("password", "refresh_token")
                .scopes("all");*/
    }

    @Override
    @SuppressWarnings("all")
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints.tokenStore(tokenStore())
                .userDetailsService(userDetailService)
                .authenticationManager(authenticationManager)
                .tokenServices(defaultTokenServices())
                .exceptionTranslator(cnswhyWebResponseExceptionTranslator);
    }

    @Bean
    public TokenStore tokenStore() {
        return new RedisTokenStore(redisConnectionFactory);
    }

    @Primary
    @Bean
    public DefaultTokenServices defaultTokenServices() {
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setTokenStore(tokenStore());
        tokenServices.setSupportRefreshToken(true); //表示开启刷新令牌的支持
        tokenServices.setAccessTokenValiditySeconds(cnswhyAuthProperties.getAccessTokenValiditySeconds());
        tokenServices.setRefreshTokenValiditySeconds(cnswhyAuthProperties.getRefreshTokenValiditySeconds());
        return tokenServices;
    }

    @Bean("uidGenerator")
    @ConditionalOnMissingBean
    public UidGenerator uidGenerator() {
        return new RedisUidGenerator();
    }
}
